package com.chanjiedata.changbs.web.ui;


import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;


import com.chanjiedata.changbs.R;
import com.chanjiedata.changbs.base.BaseFragment;
import com.chanjiedata.changbs.help.UserHelper;
import com.chanjiedata.changbs.utlis.LogUtil;
import com.chanjiedata.changbs.web.inteface.JavaScriptInterface;
import com.chanjiedata.changbs.web.manager.WebViewClientUtil;

import java.lang.ref.WeakReference;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by Frank on 2018/1/9.
 */

public class WebViewFragment extends BaseFragment implements WebViewClientUtil.WebClientLoadListener {
    @BindView(R.id.webView)
    WebView webView;
    Unbinder unbinder;

    private Handler jsInterfaceHandler = new JsInterfaceHandler(getActivity());
    private String url;

    public static WebViewFragment newInstance(String url) {
        WebViewFragment fragment = new WebViewFragment();
        Bundle bundle = new Bundle();
        bundle.putString("url", url);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_web_view;
    }

    @Override
    protected void initView() {
        url = getArguments().getString("url");
        webView.getSettings().setJavaScriptEnabled(true);
        webView.addJavascriptInterface(new JavaScriptInterface(jsInterfaceHandler), "app");
        webView.setWebViewClient(new WebViewClientUtil(getActivity(), this));
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        webView.getSettings().setLoadsImagesAutomatically(true);// 加载网页中的图片
        webView.getSettings().setUseWideViewPort(true); //设置使用视图的宽端口
        webView.getSettings().setAllowFileAccess(true);// 可以读取文件缓存(manifest生效)
//        webView.setWebChromeClient(myChromeClient = new MyChromeClient(this, mUploadMessage, mUploadCallbackAboveL,
//                this, this));
        // webView.setDownloadListener(new MyDownloadStart(this));//设置下载监听
        // webview 从Lollipop(5.0)开始webview默认不允许混合模式，https当中不能加载http资源，需要设置开启
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        if (UserHelper.isLogin()) {
            syncCookie(getActivityContext(), url);   //同步cookie
        }
        loadUrl();
    }

    @Override
    protected void init() {

    }

    private void loadUrl() {
        String newUrl;
        //统一拼接可
        if(UserHelper.isLogin()){
            if(url.contains("?")){
                newUrl = url+"&key="+UserHelper.getCurrentToken();
            }else{
                newUrl = url+"?key="+UserHelper.getCurrentToken();
            }
        }else{
            newUrl = url;
        }
        webView.loadUrl(newUrl);
        LogUtil.e("frank", "WebViewFragment网页请求地址：" + newUrl);
    }


    //同步cookie
    private void syncCookie(Context context, String url) {
        try {
            CookieSyncManager.createInstance(context);
            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.setAcceptCookie(true);
            cookieManager.removeAllCookie();
            cookieManager.setCookie(url, "key=" + UserHelper.getCurrentToken());
            String newCookie = cookieManager.getCookie(url);
            if (newCookie != null) {
                LogUtil.d("frank","设置Cookie url="+url+" ;   cookie="+ newCookie);
            }
        } catch (Exception e) {
            LogUtil.e("Frank: webView.syncCookie failed", e.toString());
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void loadFinished(String title,boolean isError) {

    }


    /*--------------------------------H5 调用原生--------------------------------*/

    private static class JsInterfaceHandler extends Handler {
        private WeakReference<Activity> weakRefActivity;
        private Activity context;

        public JsInterfaceHandler(Activity activity) {
            this.context = activity;
            weakRefActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            Activity activity = weakRefActivity.get();
            if (activity != null) {
                switch (msg.what) {

                }
            }
        }
    }
}
